<?php

namespace app\common\controller;
use app\common\lib\redis\Redis;
use app\common\model\User;
use sms\Sms as msgSms;
use app\common\lib\SmsRedis;
use app\common\lib\Util;
use think\facade\Log;

class Sms extends Base
{
    public static function sendSms($phoneNum,$route)
    {
        $reg = "/^1[345789]\d{9}$/";
        // 为空且不包括0
        if (empty($phoneNum) && $phoneNum != '0') {
            return Util::apiResponse(array(), '手机号不能为空', 400);
        }
        if (!preg_match($reg, $phoneNum)) {
            return Util::apiResponse(array(), '手机号格式不正确', 400);
        }
        $exist = User::where(['phone_num' => $phoneNum])->field('id')->find();
        $redis = Redis::getInstance();
        $req = $route . ':' . $phoneNum;
        $limitResult = self::apiLimit($req, 8, 60);
        if ($limitResult && $limitResult['code'] != 200) {
            return Util::apiResponse([], $limitResult['msg'], 429);
        }
        $code = rand(100000, 999999);
        $sendStatus = msgSms::getInstance()->send($phoneNum, $code);
        if ($sendStatus['status'] == 'success' && $sendStatus['data']['Code'] == 'OK') {
            if ($exist) {
                $redis->set(SmsRedis::loginSmsKey($phoneNum), $code,config('redis.expire_time'));
            } else {
                $redis->set(SmsRedis::regSmsKey($phoneNum), $code,config('redis.expire_time'));
            }
            //发送成功
            return Util::apiResponse(array('code' => $code), '验证码发送成功', 200);
        } else {
            //发送短信失败
            return Util::apiResponse(array(), $sendStatus['msg'], 400);
        }
    }
}